// 使用立即执行函数创建一个闭包来管理 settings
const settingsManager = (function() {
    let settings = null;

    return {
        setSettings: function(newSettings) {
            settings = newSettings;
        },
        getSettings: function() {
            return settings;
        }
    };
})();

// 在文件开头添加一个变量来存储支持的语言数量
let maxSupportedLanguages = 1;

// 修改 validateApiKey 函数
function validateApiKey(value) {
    if (!value) {
        return new Promise((resolve) => {
            resolve({
                isValid: false,
                errorOptions: {
                    message: 'Please enter your Falcon5 API key!',
                    marginBottom: 0
                }
            });
        });
    }

    // 获取输入框和其容器
    const input = document.getElementById('activityTicket');

    // 添加loading状态
    document.querySelector('.sk-spinner').style.display = "block";
    input.disabled = true;

    // 返回Promise以支持异步验证
    return new Promise((resolve) => {
        admin_app.checkApiKey(
            value,
            function(isValid, supportLanguageNum) {
                // 移除loading状态
                document.querySelector('.sk-spinner').style.display = "none"
                input.disabled = false;
                // 保存支持的语言数量
                maxSupportedLanguages = supportLanguageNum || 1;

                // 更新提示文本中的语言数量
                const hintText = document.querySelector('.hint-text span:nth-child(2)');
                if (hintText) {
                    hintText.textContent = `Current package can only be used in ${maxSupportedLanguages} languages, please upgrade your package if you need more languages.`;
                }

                // 检查并更新已选择的语言
                validateSelectedLanguages();

                resolve({
                    isValid: isValid,
                    errorOptions: isValid ? {} : {
                        message: 'Make sure you enter a valid Falcon5 API key!',
                        marginBottom: 0
                    }
                });
            },
            function(response) {
                console.error('API key验证失败:', response.code);
                // 移除loading状态
                document.querySelector('.sk-spinner').style.display = "none"
                input.disabled = false;

                // 根据 errorCode 设置不同的错误信息
                let errorOptions = {
                    message: 'Make sure you enter a valid Falcon5 API key!',
                    marginBottom: 0
                };

                if (response.code === 2004004) {
                    errorOptions = {
                        message: response.msg,
                        marginBottom: 60
                    };
                }

                if (response.code === 2000004) {
                    errorOptions = {
                        message: response.msg,
                        marginBottom: 40
                    };
                }


                resolve({
                    isValid: false,
                    errorOptions: errorOptions
                });
            }
        );
    });
}

// 添加验证选中语言数量的函数
function validateSelectedLanguages() {
    const selectedLanguages = getSelectedLanguages();
    const checkboxes = document.querySelectorAll('.language-item:not(.check-all) input[type="checkbox"]');

    if (selectedLanguages.length > maxSupportedLanguages) {
        console.log('selectedLanguages:', selectedLanguages);
        console.log('maxSupportedLanguages:', maxSupportedLanguages);
        // 如果选中的语言数量超过限制，取消最后选中的语言
        checkboxes.forEach(checkbox => {
            if (checkbox.checked && selectedLanguages.length > maxSupportedLanguages) {
                checkbox.checked = false;
                selectedLanguages.pop();
            }
        });

        // 显示提示信息
        fc5_utils.showTip(`You can only select up to ${maxSupportedLanguages} languages with your current package.`);
    }

    // 更新全选框状态
    updateCheckAllStatus();
    // 更新widget预览
    updateWidgetPreview();
    // 如果是子域名模式，更新语言链接
    if (document.querySelector('#sub-domain').checked) {
        const currentSettings = settingsManager.getSettings();
        updateLanguageLinks(currentSettings);
    }
    // 验证保存按钮状态
    validateSaveButton();
}

// 设置输入框错误状态
function setInputError(show, errorOptions = {}) {
    const wrapper = document.querySelector('#activityTicket').closest('.input-wrapper');
    wrapper.classList.toggle('show-error', show);
    wrapper.classList.toggle('show-valid', !show);
    const input = wrapper.querySelector('input');
    input.classList.toggle('valid', !show);

    // 获取错误信息元素
    const errorDiv = document.querySelector('.input-error');
    const apiKeyDiv = document.querySelector('.fc5-api-key');

    console.log('show:', show);
    console.log('errorOptions:', errorOptions);

    if (show && errorOptions ? .message) {
        // 使用 innerHTML 而不是 textContent 来支持 HTML 链接
        errorDiv.innerHTML = errorOptions.message;
        errorDiv.style.display = 'block';

        // 处理额外的样式
        if (errorOptions.marginBottom !== undefined) {
            apiKeyDiv.style.marginBottom = errorOptions.marginBottom + 'px';
        }
    } else {
        // 隐藏并清除错误信息
        errorDiv.innerHTML = '';
        errorDiv.style.display = 'none';

        // 重置margin
        apiKeyDiv.style.marginBottom = '0px';
    }
}

// 修改 ajaxLoadSavedSettings 函数
function ajaxLoadSavedSettings() {
    admin_app.getSettings(
        function(data) {
            console.log('页面设置:', data);
            loadSavedSettings(data);
            validateSaveButton();
        },
        function(error) {
            console.error('获取设置失败:', error);
            // fc5_utils.showTip(typeof error === 'string' ? error : (error.msg || '获取设置失败'));
        }
    );
}

// 修改 validateDomain 方法
function validateDomain(value, input) {
    if (!value) {
        setLinkInputStatus(input, false);
        return Promise.resolve(false);
    }

    // 获取当前语言代码
    const langCode = input.id.replace('link-', '');

    // 添加loading状态
    const wrapper = input.closest('.link-wrapper');
    wrapper.classList.add('loading');
    input.disabled = true;

    // 返回 Promise
    return new Promise((resolve) => {
        admin_app.checkDomain(
            value,
            langCode,
            function(isValid) {
                // 移除loading状态
                wrapper.classList.remove('loading');
                input.disabled = false;

                // 设置验证状态
                setLinkInputStatus(input, isValid);
                resolve(isValid);
            },
            function(error) {
                console.error('域名验证失败:', error);
                // 移除loading状态
                wrapper.classList.remove('loading');
                input.disabled = false;

                // 验证失败时设置错误状态
                setLinkInputStatus(input, false);
                // fc5_utils.showTip(typeof error === 'string' ? error : (error.msg || '域名验证失败'));
                resolve(false);
            }
        );
    });
}

// 修改 saveSettings 方法，使用 async/await 处理异步验证
async function saveSettings() {
    // 首先验证 API Key
    const apiKey = document.getElementById('activityTicket').value;
    const apiKeyValidation = await validateApiKey(apiKey);

    // 如果 API Key 无效，显示错误并返回
    if (!apiKeyValidation.isValid) {
        setInputError(true, apiKeyValidation.errorOptions);
        fc5_utils.showTip('Please enter your Falcon5 API key!');
        return;
    }

    // 验证子域名格式
    if (document.querySelector('#sub-domain').checked) {
        const linkInputs = document.querySelectorAll('.language-links input');
        const validationResults = await Promise.all(
            Array.from(linkInputs).map(input => validateDomain(input.value, input))
        );

        if (validationResults.includes(false)) {
            return; // 如果有任何验证失败，停止保存
        }
    }

    // 收集设置数据
    const settings = {
        activityTicket: apiKey,
        originalLanguage: document.querySelector('#originalLanguage .select-selected').dataset.value,
        enableCdn: document.getElementById('enableCdn').checked,
        openCacheDir: document.getElementById('openCacheDir').checked,
        showInMenu: document.querySelector('#showInMenu .select-selected').dataset.value,
        buttonDesign: {
            floatingSelector: document.querySelector('#floatingSelector .select-selected').dataset.value,
            wrapperSelector: document.querySelector('#wrapperSelector').value,
            openDirection: document.querySelector('#openDirection .select-selected').dataset.value,
            flagSize: document.querySelector('#flagSize .select-selected').dataset.value,
            flagStyle: document.querySelector('#flagStyle .select-selected').dataset.value
        },
        preview: {
            language: document.querySelector('#previewLanguage .select-selected').dataset.value,
        },
        colors: {
            switcherText: document.getElementById('switcherTextColor').value,
            switcherArrow: document.getElementById('switcherArrowColor').value,
            switcherBorder: document.getElementById('switcherBorderColor').value,
            switcherBg: document.getElementById('switcherBgColor').value,
            switcherBgShadow: document.getElementById('switcherBgShadowColor').value,
            switcherBgHover: document.getElementById('switcherBgHoverColor').value,
            dropdownText: document.getElementById('dropdownTextColor').value,
            dropdownHover: document.getElementById('dropdownHoverColor').value,
            dropdownBg: document.getElementById('dropdownBgColor').value
        },
        protocol: 'https',
        domain: document.querySelector('#domain') ? .value || 'second-inc.local',
        languageFormat: document.querySelector('input[name="format"]:checked').value,
        selectedLanguages: getSelectedLanguages(),
        languageLinks: getLanguageLinks()
    };

    // 显示保存中状态
    const saveButton = document.querySelector('.save-btn');
    const originalText = saveButton.textContent;
    saveButton.textContent = 'Saving...';
    saveButton.disabled = true;

    fc5_utils.log(JSON.stringify(settings));
    admin_app.saveSettings(
        settings,
        function(data) {
            // 恢复按钮状态
            saveButton.textContent = originalText;
            saveButton.disabled = false;
            fc5_utils.showTip('Settings saved successfully');
        },
        function(error) {
            // 恢复按钮状态
            saveButton.textContent = originalText;
            saveButton.disabled = false;
            console.error('Save settings error:', error);
            fc5_utils.showTip(typeof error === 'string' ? error : (error.msg || 'Failed to save settings'));
        }
    );
}

// 修改初始化页面的代码
document.addEventListener('DOMContentLoaded', () => {
    // 获取保存按钮
    const saveButton = document.querySelector('.save-btn');
    // 初始禁用保存按钮
    saveButton.disabled = true;

    document.querySelectorAll('.tab-btn-item').forEach(item => {
        item.addEventListener('click', (e) => switchTab(e.target));
    });

    // 初始化语言列表
    initializeLanguageGrid();
    setupEventListeners();
    initializeAllCustomSelects();
    initializeApiKeyValidation();
    ajaxLoadSavedSettings();
    handleColorPicker();

    // 立即检查是否有选中的语言
    validateSaveButton();
    handleLanguageSelection();
});

// 修改 initializeLanguageGrid 函数
function initializeLanguageGrid() {
    const grid = document.getElementById('languageGrid');

    // 清空现有内容
    grid.innerHTML = '';

    // 获取原始语言
    const originalLang = document.querySelector('#originalLanguage .select-selected') ? .dataset.value;

    // 创建语言选择区域
    const languagesContainer = document.createElement('div');
    languagesContainer.className = 'languages-container';

    // 过滤掉原始语言，只显示其他可选语言
    const availableLanguages = languages.filter(lang => lang.code !== originalLang);

    // 创建每个语言的选择项
    availableLanguages.forEach(lang => {
        const langItem = createLanguageItem(lang);
        languagesContainer.appendChild(langItem);
    });

    // 将语言容器添加到网格中
    grid.appendChild(languagesContainer);

    // 重新绑定复选框事件
    bindCheckboxEvents();

    // 在语言网格初始化完成后更新widget preview
    updateWidgetPreview();
}

// 新增函数：专门处理复选框事件绑定
function bindCheckboxEvents() {
    const checkAllBox = document.getElementById('check-all');
    const languageCheckboxes = document.querySelectorAll(
        '.language-item:not(.check-all) input[type="checkbox"]'
    );

    // 处理复选框变化的通用函数
    function handleCheckboxChange(isChecked, totalCount) {
        if (isChecked && totalCount > maxSupportedLanguages) {
            fc5_utils.showTip(`You can only select up to ${maxSupportedLanguages} languages with your current package.`);
            return false;
        }
        return true;
    }

    // 移除之前的事件监听器
    const newCheckAllBox = checkAllBox.cloneNode(true);
    checkAllBox.parentNode.replaceChild(newCheckAllBox, checkAllBox);

    // 全选框变化事件
    newCheckAllBox.addEventListener('change', e => {
        if (!handleCheckboxChange(e.target.checked, languageCheckboxes.length)) {
            e.target.checked = false;
            return;
        }

        languageCheckboxes.forEach(box => {
            box.checked = e.target.checked;
        });

        validateSelectedLanguages();
    });

    // 单个语言复选框变化事件
    languageCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', (e) => {
            if (e.target.checked) {
                const selectedCount = document.querySelectorAll(
                    '.language-item:not(.check-all) input[type="checkbox"]:checked'
                ).length;

                if (!handleCheckboxChange(true, selectedCount)) {
                    e.target.checked = false;
                    return;
                }
            }

            validateSelectedLanguages();
        });
    });
}

// 创建单个语言选择项
function createLanguageItem(lang) {
    const div = document.createElement('div');
    div.className = 'language-item';

    const checkbox = document.createElement('input');
    checkbox.type = 'checkbox';
    checkbox.id = `lang-${lang.code}`;
    checkbox.value = lang.code;
    checkbox.dataset.name = lang.name;

    const label = document.createElement('label');
    label.htmlFor = `lang-${lang.code}`;
    label.textContent = lang.name;

    div.appendChild(checkbox);
    div.appendChild(label);
    return div;
}

// 设置事件监听器
function setupEventListeners() {
    // 添加 openCacheDir 复选框的事件监听
    const openCacheDirCheckbox = document.getElementById('openCacheDir');
    if (openCacheDirCheckbox) {
        openCacheDirCheckbox.addEventListener('change', function(e) {
            if (e.target.checked) {
                // 获取缓存目录信息
                admin_app.getCacheDirectory(
                    function(data) {
                        showCacheDirectoryInfo(data);
                    },
                    function(error) {
                        console.error('获取缓存目录失败:', error);
                        // fc5_utils.showTip(typeof error === 'string' ? error : (error.msg || '获取缓存目录失败'));
                    }
                );
            } else {
                // 隐藏缓存目录信息
                hideCacheDirectoryInfo();
            }
        });
    }

    // 监听格式选择变化
    document.querySelectorAll('input[name="format"]').forEach(radio => {
        radio.addEventListener('change', (e) => {
            if (e.target.value === 'sub-domain') {
                const currentSettings = settingsManager.getSettings();
                updateLanguageLinks(currentSettings);
            } else {
                // 如果选择了sub-directory，清空链接列表
                document.querySelector('.language-links').innerHTML = '';
            }
        });
    });
}

// 更新全选复选框状态
function updateCheckAllStatus() {
    const checkAllBox = document.getElementById('check-all')
    const checkboxes = document.querySelectorAll(
        '.language-item:not(.check-all) input[type="checkbox"]'
    )
    const checkedBoxes = document.querySelectorAll(
        '.language-item:not(.check-all) input[type="checkbox"]:checked'
    )

    checkAllBox.checked = checkboxes.length === checkedBoxes.length
    checkAllBox.indeterminate =
        checkedBoxes.length > 0 && checkedBoxes.length < checkboxes.length
}

// 默认widget Preview中的语言项
const initSelectItemEls = document.querySelectorAll(
    '#previewLanguage .select-item'
)

// 更新Widget Preview中的语言项
function updateWidgetPreview() {
    const originalLang = document.querySelector('#originalLanguage .select-selected') ?.dataset.value;
    const originalLangName = document.querySelector('#originalLanguage .select-selected') ?.dataset.name;
    const selectedLanguages = getSelectedLanguages();
    const selectItemsContainer = document.querySelector('#previewLanguage .select-items');
    const previewLanguageEl = document.querySelector('#previewLanguage');

    // 清空现有的选项
    selectItemsContainer.innerHTML = '';

    // 使用选中的语言，如果没有选中任何语言，则只显示原始语言
    const languagesToShow = selectedLanguages.length > 0 ? selectedLanguages : [{
        code: originalLang,
        name: originalLangName
    }];

    // 加上原始语言，如果原始语言不在选中的语言中
    if (!languagesToShow.some(lang => lang.code === originalLang)) {
        languagesToShow.unshift({
            code: originalLang,
            name: originalLangName
        });
    }

    // 获取当前的 flag size 和 style 设置
    const currentFlagSize = document.querySelector('#flagSize .select-selected').dataset.value || '16px';
    const currentFlagStyle = document.querySelector('#flagStyle .select-selected').dataset.value || '2d';

    // 移除所有尺寸和样式类
    previewLanguageEl.classList.remove('flag-size-16', 'flag-size-24', 'flag-size-32');
    previewLanguageEl.classList.remove('flag-style-2d', 'flag-style-3d');

    // 添加当前尺寸和样式类
    previewLanguageEl.classList.add(`flag-size-${currentFlagSize.replace('px', '')}`);
    previewLanguageEl.classList.add(`flag-style-${currentFlagStyle}`);

    // 获取当前的颜色设置
    const currentDropdownTextColor = document.getElementById('dropdownTextColor').value;
    const currentDropdownHoverColor = document.getElementById('dropdownHoverColor').value;
    const currentSwitcherBgHoverColor = document.getElementById('switcherBgHoverColor').value;
    const currentSwitcherBgColor = document.getElementById('switcherBgColor').value;
    const currentSwitcherBgShadowColor = document.getElementById('switcherBgShadowColor').value;

    // 添加语言选项
    languagesToShow.forEach(language => {
        const langItem = document.createElement('div');
        langItem.classList.add('select-item');
        langItem.dataset.value = language.code;
        langItem.dataset.action = 'selectLanguage';

        langItem.innerHTML = `
            <div class="select-flag">
                <img src="${assetsUri}/images/flags/${language.code}.svg" alt="${language.name} flag">
            </div>
            <span class="select-text" style="color: ${currentDropdownTextColor};">${language.name}</span>
        `;

        // 添加悬停效果
        langItem.addEventListener('mouseover', () => {
            langItem.style.backgroundColor = currentDropdownHoverColor;
        });

        langItem.addEventListener('mouseout', () => {
            langItem.style.backgroundColor = 'transparent';
        });

        selectItemsContainer.appendChild(langItem);
    });

    // 更新当前选中的语言显示
    const currentSelect = document.querySelector('#previewLanguage .select-selected');
    const currentValue = currentSelect.dataset.value;

    // 移除之前的事件监听器
    const newCurrentSelect = currentSelect.cloneNode(true);
    currentSelect.parentNode.replaceChild(newCurrentSelect, currentSelect);

    // 应用渐变背景
    newCurrentSelect.style.background = `${currentSwitcherBgColor} linear-gradient(180deg, ${currentSwitcherBgShadowColor} 0%, ${currentSwitcherBgColor} 70%)`;

    // 添加悬停效果
    newCurrentSelect.addEventListener('mouseover', () => {
        newCurrentSelect.style.backgroundColor = currentSwitcherBgHoverColor;
        newCurrentSelect.style.background = currentSwitcherBgHoverColor;
    });

    newCurrentSelect.addEventListener('mouseout', () => {
        newCurrentSelect.style.background = `${currentSwitcherBgColor} linear-gradient(180deg, ${currentSwitcherBgShadowColor} 0%, ${currentSwitcherBgColor} 70%)`;
    });

    // 重新添加点击事件处理器
    newCurrentSelect.addEventListener('click', (e) => {
        e.stopPropagation();
        newCurrentSelect.classList.toggle('active');
        selectItemsContainer.classList.toggle('select-hide');
    });

    // 点击外部关闭下拉列表
    document.addEventListener('click', (e) => {
        if (!previewLanguageEl.contains(e.target)) {
            newCurrentSelect.classList.remove('active');
            selectItemsContainer.classList.add('select-hide');
        }
    });

    // 如果当前选中的语言不在可用列表中，设置为第一个可用语言
    if (!languagesToShow.some(lang => lang.code === currentValue)) {
        const firstLang = languagesToShow[0];
        newCurrentSelect.innerHTML = `
            <div class="select-flag">
                <img src="${assetsUri}/images/flags/${firstLang.code}.svg" alt="${firstLang.name} flag">
            </div>
            <span class="select-text">${firstLang.name}</span>
            <span class="select-arrow"></span>
        `;
        newCurrentSelect.dataset.value = firstLang.code;
    }
}

// 加载保存的设置
function loadSavedSettings(settings) {
    if (!settings) return;

    // 使用 settingsManager 存储设置
    settingsManager.setSettings(settings);

    // 处理 buttonDesign 相关的设置
    if (settings.buttonDesign) {
        // Show floating language selector
        const floatingSelector = document.querySelector('#floatingSelector .select-selected');
        if (floatingSelector && settings.buttonDesign.floatingSelector) {
            floatingSelector.setAttribute('data-value', settings.buttonDesign.floatingSelector);
            // 找到对应的选项文本
            floatingSelector.querySelector('.select-text').textContent = {
                'none': '- None -',
                'bottom-left': 'Bottom Left',
                'bottom-right': 'Bottom Right',
                'top-left': 'Top Left',
                'top-right': 'Top Right'
            }[settings.buttonDesign.floatingSelector] || '- None -';
        }

        // Open direction
        const openDirection = document.querySelector('#openDirection .select-selected');
        if (openDirection && settings.buttonDesign.openDirection) {
            openDirection.setAttribute('data-value', settings.buttonDesign.openDirection);
            // 首字母大写
            openDirection.querySelector('.select-text').textContent = settings.buttonDesign.openDirection.charAt(0).toUpperCase() +
                settings.buttonDesign.openDirection.slice(1);
        }

        // Flag size
        const flagSize = document.querySelector('#flagSize .select-selected');
        if (flagSize && settings.buttonDesign.flagSize) {
            flagSize.setAttribute('data-value', settings.buttonDesign.flagSize);
            flagSize.querySelector('.select-text').textContent = settings.buttonDesign.flagSize;

            // 应用到 widget preview
            const previewLanguageEl = document.querySelector('#previewLanguage');

            // 移除所有尺寸类
            previewLanguageEl.classList.remove('flag-size-16', 'flag-size-24', 'flag-size-32');

            // 添加新的尺寸类
            const newSize = settings.buttonDesign.flagSize.replace('px', '');
            previewLanguageEl.classList.add(`flag-size-${newSize}`);
        }

        // Flag style
        const flagStyle = document.querySelector('#flagStyle .select-selected');
        if (flagStyle && settings.buttonDesign.flagStyle) {
            const style = settings.buttonDesign.flagStyle.toUpperCase();
            flagStyle.setAttribute('data-value', settings.buttonDesign.flagStyle);
            flagStyle.querySelector('.select-text').textContent = style;

            // 应用到 widget preview
            const previewLanguageEl = document.querySelector('#previewLanguage');

            // 移除所有样式类
            previewLanguageEl.classList.remove('flag-style-2d', 'flag-style-3d');

            // 添加新的样式类
            previewLanguageEl.classList.add(`flag-style-${settings.buttonDesign.flagStyle.toLowerCase()}`);
        }

        // Wrapper selector
        const wrapperSelector = document.querySelector('#wrapperSelector');
        if (wrapperSelector && settings.buttonDesign.wrapperSelector) {
            wrapperSelector.value = settings.buttonDesign.wrapperSelector;
        }
    }

    if (settings.activityTicket) {
        document.getElementById('activityTicket').value = settings.activityTicket;
    }

    // 设置原始语言
    if (settings.originalLanguage) {
        const value = settings.originalLanguage;
        const item = document.querySelector(`#originalLanguage .select-item[data-value="${value}"]`);
        if (item) {
            const selected = document.querySelector('#originalLanguage .select-selected');
            const flag = item.querySelector('img').cloneNode(true);
            const text = item.querySelector('.select-text').textContent;

            selected.dataset.value = value;
            selected.querySelector('.select-flag img').replaceWith(flag);
            selected.querySelector('.select-text').textContent = text;

            document.querySelectorAll('#originalLanguage .select-item').forEach(el => {
                el.classList.toggle('selected', el.dataset.value === value);
            });
        }
    }

    document.getElementById('enableCdn').checked = settings.enableCdn;
    document.getElementById('openCacheDir').checked = settings.openCacheDir;
    // Show in menu
    const showInMenuEl = document.querySelector('#showInMenu .select-selected');
    if (showInMenuEl && settings.showInMenu) {
        showInMenuEl.dataset.value = settings.showInMenu;
        const selectedText = showInMenuEl.querySelector('.select-text');
        const items = document.querySelectorAll('#showInMenu .select-item');

        items.forEach(item => {
            if (item.dataset.value === settings.showInMenu) {
                selectedText.textContent = item.querySelector('.select-text').textContent;
                item.classList.add('selected');
            } else {
                item.classList.remove('selected');
            }
        });
    }

    // 设置颜色并应用到 widget preview
    if (settings.colors) {
        const previewLanguageEl = document.querySelector('#previewLanguage');
        const selectSelectedEl = previewLanguageEl.querySelector('.select-selected');
        const selectSelectedTextEl = selectSelectedEl.querySelector('.select-text');
        const selectSelectedArrowEl = selectSelectedEl.querySelector('.select-arrow');
        const selectItems = previewLanguageEl.querySelector('.select-items');

        // 设置并应用文本颜色
        if (settings.colors.switcherText) {
            document.getElementById('switcherTextColor').value = settings.colors.switcherText;
            selectSelectedTextEl.style.color = settings.colors.switcherText;
        }

        // 设置并应用箭头颜色
        if (settings.colors.switcherArrow) {
            document.getElementById('switcherArrowColor').value = settings.colors.switcherArrow;
            selectSelectedArrowEl.style.borderColor = settings.colors.switcherArrow;
        }

        // 设置并应用边框颜色
        if (settings.colors.switcherBorder) {
            document.getElementById('switcherBorderColor').value = settings.colors.switcherBorder;
            selectSelectedEl.style.borderColor = settings.colors.switcherBorder;
        }

        // 设置并应用背景颜色
        if (settings.colors.switcherBg) {
            document.getElementById('switcherBgColor').value = settings.colors.switcherBg;
            selectSelectedEl.style.backgroundColor = settings.colors.switcherBg;
        }

        // 设置并应用阴影颜色
        if (settings.colors.switcherBgShadow) {
            document.getElementById('switcherBgShadowColor').value = settings.colors.switcherBgShadow;
            selectSelectedEl.style.boxShadow = `0 0 5px 0 ${settings.colors.switcherBgShadow}`;
        }

        // 设置并应用下拉框文本颜色
        if (settings.colors.dropdownText) {
            document.getElementById('dropdownTextColor').value = settings.colors.dropdownText;
            selectItems.querySelectorAll('.select-item').forEach(item => {
                const textEl = item.querySelector('.select-text');
                if (textEl) {
                    textEl.style.color = settings.colors.dropdownText;
                }
            });
        }

        // 设置并应用下拉框背景颜色
        if (settings.colors.dropdownBg) {
            document.getElementById('dropdownBgColor').value = settings.colors.dropdownBg;
            selectItems.style.backgroundColor = settings.colors.dropdownBg;
        }

        // 设置悬停效果
        if (settings.colors.switcherBgHover) {
            document.getElementById('switcherBgHoverColor').value = settings.colors.switcherBgHover;
            const hoverColor = settings.colors.switcherBgHover;

            selectSelectedEl.addEventListener('mouseover', () => {
                selectSelectedEl.style.backgroundColor = hoverColor;
            });

            selectSelectedEl.addEventListener('mouseout', () => {
                selectSelectedEl.style.backgroundColor = settings.colors.switcherBg || '';
            });
        }

        // 设置下拉项悬停效果
        if (settings.colors.dropdownHover) {
            document.getElementById('dropdownHoverColor').value = settings.colors.dropdownHover;
            const hoverColor = settings.colors.dropdownHover;

            selectItems.querySelectorAll('.select-item').forEach(item => {
                item.addEventListener('mouseover', () => {
                    item.style.backgroundColor = hoverColor;
                });

                item.addEventListener('mouseout', () => {
                    item.style.backgroundColor = 'transparent';
                });
            });
        }
    }

    // 设置选中的语言
    if (settings.selectedLanguages && settings.selectedLanguages.length > 0) {
        settings.selectedLanguages.forEach(lang => {
            const checkbox = document.querySelector(`#lang-${lang.code}`);
            if (checkbox) {
                checkbox.checked = true;
            }
        });
        // 更新全选框状态
        updateCheckAllStatus();
        // 更新 widget preview
        updateWidgetPreview();
        // 检查保存按钮状态
        validateSaveButton();
    }

    // 设置语言格式
    if (settings.languageFormat) {
        document.querySelector(`input[name="format"][value="${settings.languageFormat}"]`).checked = true;

        // 如果是子域名格式，需要更新链接列表并填充保存的值
        if (settings.languageFormat === 'sub-domain') {
            updateLanguageLinks(settings);

            // 如果存在已保存的语言链接，填充到对应的输入框
            if (settings.languageLinks) {
                Object.entries(settings.languageLinks).forEach(([langCode, domain]) => {
                    const input = document.querySelector(`#link-${langCode}`);
                    if (input) {
                        input.value = domain;
                        // 验证并设置输入框状态
                        validateDomain(domain, input);
                    }
                });
            }
        }
    }

    // 设置预览语言
    if (settings.preview) {
        const value = settings.preview.language;
        const item = document.querySelector(`#previewLanguage .select-item[data-value="${value}"]`);
        if (item) {
            const selected = document.querySelector('#previewLanguage .select-selected');
            const flag = item.querySelector('img').cloneNode(true);
            const text = item.querySelector('.select-text').textContent;

            selected.dataset.value = value;
            selected.querySelector('.select-flag img').replaceWith(flag);
            selected.querySelector('.select-text').textContent = text;

            document.querySelectorAll('#previewLanguage .select-item').forEach(el => {
                el.classList.toggle('selected', el.dataset.value === value);
            });
        }
    }

    // 设置 openCacheDir 的状态并触发事件
    const openCacheDirCheckbox = document.getElementById('openCacheDir');
    if (openCacheDirCheckbox) {
        openCacheDirCheckbox.checked = settings.openCacheDir;
        if (settings.openCacheDir) {
            // 如果是选中状态,获取并显示缓存目录信息
            admin_app.getCacheDirectory(
                function(data) {
                    showCacheDirectoryInfo(data);
                },
                function(error) {
                    console.error('获取缓存目录失败:', error);
                    // fc5_utils.showTip(typeof error === 'string' ? error : (error.msg || '获取缓存目录失败'));
                }
            );
        }
    }
}

// 获取选中的语言列表
function getSelectedLanguages() {
    const checkedBoxes = document.querySelectorAll('.language-item:not(.check-all) input[type="checkbox"]:checked');
    return Array.from(checkedBoxes).map(checkbox => ({
        code: checkbox.value,
        name: checkbox.dataset.name
    }));
}

// 切换tab
function switchTab(tab) {
    document.querySelectorAll('.tab-btn-item').forEach((item, index) => {
        item.classList.remove('action');
        document.querySelector(`.${item.dataset.tab}`).classList.remove('active');
    });
    tab.classList.add('action');
    document.querySelector(`.${tab.dataset.tab}`).classList.add('active');
}

document.querySelectorAll('.tab-btn-item').forEach(item => {
    item.addEventListener('click', e => switchTab(e.target))
})

// 初始化所有自定义下拉框
function initializeAllCustomSelects() {
    const customSelects = document.querySelectorAll('.custom-select');

    // 在点击任何地方时，关闭所有打开的下拉框
    document.addEventListener('click', function(e) {
        if (!e.target.closest('.custom-select')) {
            customSelects.forEach(select => {
                const selected = select.querySelector('.select-selected');
                const itemsContainer = select.querySelector('.select-items');
                selected.classList.remove('active');
                itemsContainer.classList.add('select-hide');
            });
        }
    });

    customSelects.forEach(select => {
        initializeCustomSelect(select, customSelects);
    });
}

// 自定义下拉框处理
function initializeCustomSelect(selectContainer, customSelects) {
    const selected = selectContainer.querySelector('.select-selected');
    const itemsContainer = selectContainer.querySelector('.select-items');
    const isOriginalLanguage = selectContainer.id === 'originalLanguage';

    // 点击选中项时显示/隐藏选项列表
    selected.addEventListener('click', function(e) {
        e.stopPropagation();

        // 关闭其他下拉框
        customSelects.forEach(select => {
            if (select !== selectContainer) {
                const otherSelected = select.querySelector('.select-selected');
                const otherItemsContainer = select.querySelector('.select-items');
                otherSelected.classList.remove('active');
                otherItemsContainer.classList.add('select-hide');
            }
        });

        // 切换当前下拉框的显示状态
        this.classList.toggle('active');
        itemsContainer.classList.toggle('select-hide');
    });

    // 点击选项时更新选中项
    itemsContainer.addEventListener('click', function(e) {
        const target = e.target.closest(
            '[data-action="selectLanguage"], [data-action="selectOption"]'
        );
        if (!target) return;

        const value = target.dataset.value;
        if (!value) return;

        const text = target.querySelector('.select-text').textContent;

        // 更新选中项的显示
        selected.dataset.value = value;
        if (target.querySelector('.select-flag')) {
            const flag = target.querySelector('img').cloneNode(true);
            selected.querySelector('.select-flag img').replaceWith(flag);
        }
        selected.querySelector('.select-text').textContent = text;

        // 更新选中状态
        itemsContainer.querySelectorAll('.select-item').forEach(item => {
            item.classList.toggle('selected', item.dataset.value === value);
        });

        // 关闭下拉框
        selected.classList.remove('active');
        itemsContainer.classList.add('select-hide');

        // 处理原始语言选择
        if (isOriginalLanguage) {
            selected.dataset.name = target.dataset.name;
            // 重新初始化语言网格
            initializeLanguageGrid();
            // 如果是子域名模式，更新语言链接
            if (document.querySelector('#sub-domain').checked) {
                const currentSettings = settingsManager.getSettings();
                updateLanguageLinks(currentSettings);
            }
            // 验证选中的语言
            validateSelectedLanguages();
        }

        // 处理 flag size 变化
        if (selectContainer.id === 'flagSize') {
            const previewLanguageEl = document.querySelector('#previewLanguage');
            // 移除所有尺寸类
            previewLanguageEl.classList.remove('flag-size-16', 'flag-size-24', 'flag-size-32');
            // 添加新的尺寸类
            const newSize = value.replace('px', '');
            previewLanguageEl.classList.add(`flag-size-${newSize}`);
        }

        // 处理 flag style 变化
        if (selectContainer.id === 'flagStyle') {
            const previewLanguageEl = document.querySelector('#previewLanguage');
            // 移除所有样式类
            previewLanguageEl.classList.remove('flag-style-2d', 'flag-style-3d');
            // 添加新的样式类
            previewLanguageEl.classList.add(`flag-style-${value.toLowerCase()}`);

            // 更新所有国旗图标的样式
            const allFlagImages = previewLanguageEl.querySelectorAll('.select-flag img');
            allFlagImages.forEach(img => {
                img.style.filter = value.toLowerCase() === '3d' ?
                    'drop-shadow(0px 0px 4px #999)' : 'unset';
            });
        }

        // 触发change事件
        console.log(`${selectContainer.id} changed to:`, value);
    });
}

// 初始化API key验证
function initializeApiKeyValidation() {
    const input = document.getElementById('activityTicket');
    let validateTimeout;

    // 处理验证结果的辅助函数
    const handleValidationResult = (result) => {
        setInputError(!result.isValid, result.errorOptions);
    };

    input.addEventListener('input', (e) => {
        // 清除之前的timeout
        if (validateTimeout) {
            clearTimeout(validateTimeout);
        }

        // 延迟500ms后验证,避免频繁验证
        validateTimeout = setTimeout(() => {
            validateApiKey(e.target.value.trim())
                .then(handleValidationResult);
        }, 500);
    });

    input.addEventListener('blur', (e) => {
        // 清除之前的timeout
        if (validateTimeout) {
            clearTimeout(validateTimeout);
        }
        document.querySelector('.input-wrapper').classList.remove('show-valid');
        document.querySelector('#activityTicket').classList.remove('valid');
        validateApiKey(e.target.value.trim())
            .then(handleValidationResult);
    });

    // 初始验证
    if (input.value) {
        validateApiKey(input.value.trim())
            .then(handleValidationResult);
    }
}

// 设置链接输入框的状态
function setLinkInputStatus(input, isValid) {
    const wrapper = input.closest('.link-wrapper');
    const linkContent = wrapper.closest('.link-content');
    const successIcon = linkContent.querySelector('.input-icon img[alt="succeed"]').closest('.input-icon');
    const errorIcon = linkContent.querySelector('.input-icon img[alt="retry"]').closest('.input-icon');
    const errorMessage = linkContent.querySelector('.input-error');

    // 设置验证状态类
    wrapper.classList.toggle('show-error', !isValid);
    wrapper.classList.toggle('show-valid', isValid);

    // 根据验证结果显示/隐藏对应的图标和错误信息
    if (isValid) {
        successIcon.style.display = 'block';
        errorIcon.style.display = 'none';
        errorMessage.style.display = 'none';
    } else {
        successIcon.style.display = 'none';
        errorIcon.style.display = 'block';
        errorMessage.style.display = 'block';
    }
}

// 创建语言链接项
function createLinkItem(lang, protocol = 'http', domain = 'second-inc.local') {
    const div = document.createElement('div');
    div.className = 'link-item';

    const langName = document.createElement('div');
    langName.className = 'language-name';
    langName.textContent = lang.name;

    const linkContent = document.createElement('div');
    linkContent.className = 'link-content';

    const httpPrefix = document.createElement('div');
    httpPrefix.className = 'http-prefix';
    httpPrefix.textContent = protocol + '://';

    const linkWrapper = document.createElement('div');
    linkWrapper.className = 'link-wrapper';

    const input = document.createElement('input');
    input.type = 'text';
    input.id = `link-${lang.code}`;
    input.value = `${lang.code}`;
    input.placeholder = `${lang.code}`;

    const domainSuffix = document.createElement('div');
    domainSuffix.className = 'domain-suffix';
    domainSuffix.textContent = '.' + domain;

    const icon = document.createElement('div');
    icon.className = 'input-icon';
    icon.innerHTML = '<img src="' + `${assetsUri}` + '/images/page/succeed.svg" alt="succeed">';

    const errorIcon = document.createElement('div');
    errorIcon.className = 'input-icon';
    errorIcon.innerHTML = '<img src="' + `${assetsUri}` + '/images/page/retry.svg" alt="retry">';

    const error = document.createElement('div');
    error.className = 'input-error';
    error.textContent = 'Invalid domain name please re-verify';

    linkWrapper.appendChild(input);

    linkContent.appendChild(httpPrefix);
    linkContent.appendChild(linkWrapper);
    linkContent.appendChild(domainSuffix);
    linkContent.appendChild(icon);
    linkContent.appendChild(errorIcon);
    linkContent.appendChild(error);

    div.appendChild(langName);
    div.appendChild(linkContent);

    // 添加验证事件
    input.addEventListener('input', (e) => {
        validateDomain(e.target.value, e.target);
    });

    input.addEventListener('blur', (e) => {
        validateDomain(e.target.value, e.target);
    });

    return div;
}

// 更新语言链接列表
function updateLanguageLinks(settings = {}) {
    console.log('updateLanguageLinks', settings);
    const linksContainer = document.querySelector('.language-links');
    linksContainer.innerHTML = ''; // 清空现有内容

    // 获取选中的语言
    const selectedLanguages = getSelectedLanguages();
    const originalLanguage = document.querySelector('#originalLanguage .select-selected').dataset.value;

    // 使用传入的 settings，如果没有则使用默认值
    const protocol = settings.protocol || 'https';
    const domain = settings.domain || 'second-inc.local';

    // 为每个选中的语言创建链接输入框
    selectedLanguages.forEach(lang => {
        if (lang.code === originalLanguage) {
            return;
        }
        const linkItem = createLinkItem(lang, protocol, domain);
        linksContainer.appendChild(linkItem);
    });
}

/**
 * Handle color picker changes
 */
function handleColorPicker() {
    // Color inputs mapping with their corresponding style properties
    const colorInputs = {
        'switcherTextColor': {
            selector: '#switcherTextColor',
            apply: (value, currentSelect) => {
                const textEl = currentSelect.querySelector('.select-text');
                if (textEl) textEl.style.color = value;
            }
        },
        'switcherArrowColor': {
            selector: '#switcherArrowColor',
            apply: (value, currentSelect) => {
                const arrowEl = currentSelect.querySelector('.select-arrow');
                if (arrowEl) arrowEl.style.borderColor = value;
            }
        },
        'switcherBorderColor': {
            selector: '#switcherBorderColor',
            apply: (value, currentSelect) => {
                currentSelect.style.border = `1px solid ${value}`;
            }
        },
        'switcherBgColor': {
            selector: '#switcherBgColor',
            apply: (value, currentSelect, colors) => {
                const shadowColor = document.querySelector('#switcherBgShadowColor') ? .value || colors.switcherBgShadow;
                currentSelect.style.background = `${value} linear-gradient(180deg, ${shadowColor} 0%, ${value} 70%)`;
            }
        },
        'switcherBgShadowColor': {
            selector: '#switcherBgShadowColor',
            apply: (value, currentSelect, colors) => {
                const bgColor = document.querySelector('#switcherBgColor') ? .value || colors.switcherBg;
                currentSelect.style.background = `${bgColor} linear-gradient(180deg, ${value} 0%, ${bgColor} 70%)`;
            }
        },
        'switcherBgHoverColor': {
            selector: '#switcherBgHoverColor',
            apply: (value, currentSelect) => {
                // Hover effect will be handled in updateWidgetPreview
            }
        },
        'dropdownTextColor': {
            selector: '#dropdownTextColor',
            apply: (value, _, __, selectItems) => {
                selectItems.querySelectorAll('.select-text').forEach(text => {
                    text.style.color = value;
                });
            }
        },
        'dropdownHoverColor': {
            selector: '#dropdownHoverColor',
            apply: (value) => {
                // Hover effect will be handled in updateWidgetPreview
            }
        },
        'dropdownBgColor': {
            selector: '#dropdownBgColor',
            apply: (value, _, __, selectItems) => {
                selectItems.style.backgroundColor = value;
            }
        }
    };

    // Add input and change event listeners to all color inputs
    Object.entries(colorInputs).forEach(([key, config]) => {
        const input = document.querySelector(config.selector);
        if (!input) return;

        ['input', 'change'].forEach(eventType => {
            input.addEventListener(eventType, () => {
                const previewLanguageEl = document.querySelector('#previewLanguage');
                const currentSelect = previewLanguageEl ? .querySelector('.select-selected');
                const selectItems = previewLanguageEl ? .querySelector('.select-items');

                if (!currentSelect || !selectItems) return;

                // Get all current colors
                const colors = Object.fromEntries(
                    Object.entries(colorInputs).map(([k, c]) => [
                        k,
                        document.querySelector(c.selector) ? .value
                    ])
                );

                // Apply the color change
                config.apply(input.value, currentSelect, colors, selectItems);

                // Update hover effects
                updateHoverEffects(currentSelect, selectItems, colors);
            });
        });
    });
}

/**
 * Update hover effects for widget preview elements
 */
function updateHoverEffects(currentSelect, selectItems, colors) {
    // Remove existing hover listeners
    const newCurrentSelect = currentSelect.cloneNode(true);
    currentSelect.parentNode.replaceChild(newCurrentSelect, currentSelect);

    // Add hover effect to switcher
    newCurrentSelect.addEventListener('mouseover', () => {
        if (colors.switcherBgHoverColor) {
            newCurrentSelect.style.background = colors.switcherBgHoverColor;
        }
    });

    newCurrentSelect.addEventListener('mouseout', () => {
        if (colors.switcherBgColor && colors.switcherBgShadowColor) {
            newCurrentSelect.style.background = `${colors.switcherBgColor} linear-gradient(180deg, ${colors.switcherBgShadowColor} 0%, ${colors.switcherBgColor} 70%)`;
        }
    });

    // Reattach click handler for dropdown toggle
    newCurrentSelect.addEventListener('click', (e) => {
        e.stopPropagation();
        newCurrentSelect.classList.toggle('active');
        selectItems.classList.toggle('select-hide');
    });

    // Add hover effect to dropdown items
    selectItems.querySelectorAll('.select-item').forEach(item => {
        const newItem = item.cloneNode(true);
        item.parentNode.replaceChild(newItem, item);

        // Add hover effect
        newItem.addEventListener('mouseover', () => {
            if (colors.dropdownHoverColor) {
                newItem.style.backgroundColor = colors.dropdownHoverColor;
            }
        });

        newItem.addEventListener('mouseout', () => {
            newItem.style.backgroundColor = 'transparent';
        });

        // Reattach click handler for language selection
        newItem.addEventListener('click', (e) => {
            const langCode = newItem.dataset.value;
            const langName = newItem.querySelector('.select-text') ? .textContent;
            if (!langCode || !langName) return;

            // Update selected language display
            const flagSize = document.querySelector('#flagSize .select-selected') ? .dataset.value || '16px';
            const flagStyle = document.querySelector('#flagStyle .select-selected') ? .dataset.value || '2d';

            newCurrentSelect.innerHTML = `
                <div class="select-flag">
                    <img src="${assetsUri}/images/flags/${langCode}.svg" alt="${langName} flag"
                         style="filter: ${flagStyle === '3d' ? 'drop-shadow(0px 0px 4px #999)' : 'unset'};">
                </div>
                <span class="select-text" style="color: ${colors.switcherTextColor}">${langName}</span>
                <span class="select-arrow"></span>
            `;

            newCurrentSelect.dataset.value = langCode;
            newCurrentSelect.classList.remove('active');
            selectItems.classList.add('select-hide');

            // Mark selected item
            selectItems.querySelectorAll('.select-item').forEach(item => {
                item.classList.toggle('selected', item === newItem);
            });
        });
    });

    // Add document click handler to close dropdown
    document.addEventListener('click', (e) => {
        if (!e.target.closest('#previewLanguage')) {
            newCurrentSelect.classList.remove('active');
            selectItems.classList.add('select-hide');
        }
    });
}

// 验证保存按钮状态
function validateSaveButton() {
    const saveButton = document.querySelector('.save-btn');
    const checkedBoxes = document.querySelectorAll('.language-item:not(.check-all) input[type="checkbox"]:checked');
    console.log('Checked languages:', checkedBoxes.length); // 添加调试日志

    saveButton.disabled = checkedBoxes.length === 0;
}

/**
 * Handle language selection in preview
 */
function handleLanguageSelection() {
    const previewLanguageEl = document.querySelector('#previewLanguage');
    if (!previewLanguageEl) return;

    // Delegate click events for language items
    previewLanguageEl.addEventListener('click', function(e) {
        const langItem = e.target.closest('.select-item');
        if (!langItem) return;

        const currentSelect = previewLanguageEl.querySelector('.select-selected');
        const selectItems = previewLanguageEl.querySelector('.select-items');
        if (!currentSelect || !selectItems) return;

        // Get language data safely
        const langCode = langItem.dataset.value;
        const langName = langItem.querySelector('.select-text') ? .textContent;
        if (!langCode || !langName) return;

        // Get current settings safely
        const flagSizeEl = document.querySelector('#flagSize .select-selected');
        const flagStyleEl = document.querySelector('#flagStyle .select-selected');
        const flagSize = flagSizeEl ? .dataset.value || '16px';
        const flagStyle = flagStyleEl ? .dataset.value || '2d';

        // Update selected language display
        currentSelect.innerHTML = `
            <div class="select-flag">
                <img src="${assetsUri}/images/flags/${langCode}.svg" alt="${langName} flag"
                     style="filter: ${flagStyle === '3d' ? 'drop-shadow(0px 0px 4px #999)' : 'unset'};">
            </div>
            <span class="select-text">${langName}</span>
            <span class="select-arrow"></span>
        `;

        // Update data and UI state
        currentSelect.dataset.value = langCode;
        currentSelect.classList.remove('active');
        selectItems.classList.add('select-hide');

        // Mark selected item
        selectItems.querySelectorAll('.select-item').forEach(item => {
            item.classList.toggle('selected', item === langItem);
        });
    });
}

// 修改显示缓存目录信息的函数
function showCacheDirectoryInfo(data) {
    let infoDiv = document.getElementById('cacheDirectoryInfo');

    // 如果信息div不存在则创建
    if (!infoDiv) {
        infoDiv = document.createElement('div');
        infoDiv.id = 'cacheDirectoryInfo';
        infoDiv.className = 'cache-directory-info';

        // 找到 openCacheDir 复选框所在的 form-group
        const formGroup = document.getElementById('openCacheDir').closest('.form-group');
        // 将信息div插入到 form-group 后面
        formGroup.parentNode.insertBefore(infoDiv, formGroup.nextSibling);
    }

    // 创建目录路径显示
    const pathDiv = document.createElement('div');
    pathDiv.className = 'directory-path';

    // 添加目录路径文本
    const pathText = document.createElement('span');
    pathText.textContent = data.path;
    pathDiv.appendChild(pathText);

    // 添加可写状态指示器
    const writableStatus = document.createElement('span');
    writableStatus.className = `writable-status ${data.writable ? 'writable' : 'not-writable'}`;
    writableStatus.textContent = data.writable ? 'writable' : 'not writable';
    pathDiv.appendChild(writableStatus);

    // 清空并更新信息div
    infoDiv.innerHTML = '';
    infoDiv.appendChild(pathDiv);
}

// 添加隐藏缓存目录信息的函数
function hideCacheDirectoryInfo() {
    const infoDiv = document.getElementById('cacheDirectoryInfo');
    if (infoDiv) {
        infoDiv.remove();
    }
}

// 获取语言链接列表
function getLanguageLinks() {
    const links = {};
    const linkInputs = document.querySelectorAll('.language-links input');

    linkInputs.forEach(input => {
        // 从input的id中获取语言代码，格式为 'link-{langCode}'
        const langCode = input.id.replace('link-', '');
        links[langCode] = input.value.trim();
    });

    return links;
}
